#!/usr/bin/env python
#################################################################################
# Copyright 2018 ROBOTIS CO., LTD.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#################################################################################

# Authors: Jialun Li #
#coding=utf-8
import rospy
import time
from geometry_msgs.msg import Twist, Point, Quaternion
import tf
from math import radians, copysign, sqrt, pow, pi, atan2,cos,sin
from tf.transformations import euler_from_quaternion
import numpy as np
from sensor_msgs.msg import LaserScan

msg = """
control your Turtlebot3!
-----------------------
this is leader
-----------------------
"""
delta_x=1.0
position=Point()
class GotoPoint():
    def __init__(self):
        rospy.init_node('leader', anonymous=False)
        rospy.on_shutdown(self.shutdown)
        self.cmd_vel = rospy.Publisher('cmd_vel', Twist, queue_size=5)
        self.tb_leader_positon=rospy.Publisher('/tb_leader_pos',Point,queue_size=5)
        self.tb_leader_vel=rospy.Publisher('/tb_leader_vel',Twist,queue_size=5)#5
        r = rospy.Rate(10)
        self.tf_listener = tf.TransformListener()
        self.odom_frame = '/leader/odom'
        try:
            self.tf_listener.waitForTransform(self.odom_frame, '/leader/base_footprint', rospy.Time(), rospy.Duration(1.0))
            self.base_frame = '/leader/base_footprint'
        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            try:
                self.tf_listener.waitForTransform(self.odom_frame, '/leader/base_link', rospy.Time(), rospy.Duration(1.0))
                self.base_frame = '/leader/base_link'
            except (tf.Exception, tf.ConnectivityException, tf.LookupException):
                rospy.loginfo("Cannot find transform between odom and base_link or base_footprint")
                rospy.signal_shutdown("tf Exception")
        
        """
        get data from sensors
        """
        """
        publish messages
        """
        leader_vel=Twist()

        self.tb_leader_vel.publish(leader_vel)
        
        pub_position=Point()
        (position, rotation) = self.get_odom()
        
        pub_position.x=position.x+delta_x
        pub_position.y=position.y
        pub_position.z=position.z
        self.tb_leader_positon.publish(pub_position)
        
        if position.x<3:
          leader_vel.linear.x=0.1
        elif  position.x>=3 and position.x<4:
          leader_vel.linear.x=0.4-0.1*position.x
        else:
          leader_vel.linear.x=0

        leader_vel.angular.z=0
        
        self.cmd_vel.publish(leader_vel)
    	

    def get_odom(self):
        try:
            (trans, rot) = self.tf_listener.lookupTransform(self.odom_frame, self.base_frame, rospy.Time(0))
            rotation = euler_from_quaternion(rot)

        except (tf.Exception, tf.ConnectivityException, tf.LookupException):
            rospy.loginfo("TF Exception")
            return

        return (Point(*trans), rotation[2])
    def shutdown(self):
        self.cmd_vel.publish(Twist())
        rospy.sleep(1)


    def lidar(self,tb_pos):
        msg = rospy.wait_for_message("scan", LaserScan)
        LIDAR_ERR = 0.05
        LIDAR_MAX = 1.5
        obstacle=[]
        min_dis=10
        min_ang=0
        min_point=Point()
        for i in range(360):
            if i <= 45 or i > 315:
                obstacle_pos=Point()
                if msg.ranges[i] >= LIDAR_ERR and msg.ranges[i]<=LIDAR_MAX:
                    obstacle_pos.x=tb_pos.x+msg.ranges[i]*cos(i)
                    obstacle_pos.y=tb_pos.y+msg.ranges[i]*sin(i)
                    obstacle.append(obstacle_pos)
                    if msg.ranges[i] < min_dis:
                            min_dis = msg.ranges[i]
                            min_ang = i
        if min_dis<10:
            min_point.x=tb_pos.x+min_dis*cos(i)
            min_point.y=tb_pos.y+min_dis*sin(i)
        else:
            min_point.x=10
        return min_point


if __name__ == '__main__':
    try:
        while not rospy.is_shutdown():
            print(msg)
            GotoPoint()

    except:
        rospy.loginfo("shutdown program.")

